<template>
  <div 
    :class="[
      'bx-tree-select',
      'bx-glass',
      {
        'bx-tree-select--disabled': disabled,
        'bx-tree-select--focused': showDropdown
      }
    ]"
    v-click-outside="handleClickOutside"
  >
    <div 
      class="bx-tree-select__input"
      @click="toggleDropdown"
    >
      <input
        type="text"
        :value="displayValue"
        :placeholder="placeholder"
        :disabled="disabled"
        readonly
        class="bx-tree-select__input-field"
      />
      <BxIcon name="chevron-down" class="bx-tree-select__arrow" />
      <BxIcon 
        v-if="clearable && displayValue"
        name="x-circle"
        class="bx-tree-select__clear"
        @click.stop="handleClear"
      />
    </div>

    <div 
      v-if="showDropdown"
      class="bx-tree-select__dropdown bx-glass"
    >
      <BxTree
        :data="options"
        :checkable="multiple"
        :expand-all="true"
        :selected-value="selectedValues"
        @change="handleTreeChange"
      />
      <div v-if="!options || options.length === 0" class="bx-tree-select__empty">
        <BxEmpty description="无数据" size="small" />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import BxIcon from '../basic/BxIcon.vue'
import BxTree from '../data-display/BxTree.vue'
import BxEmpty from '../data-display/BxEmpty.vue'

export default {
  name: 'BxTreeSelect',
  components: {
    BxIcon,
    BxTree,
    BxEmpty
  },
  props: {
    modelValue: {
      type: [String, Number, Array],
      default: null
    },
    options: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'medium',
      validator: (value) => ['small', 'medium', 'large'].includes(value)
    }
  },
  emits: ['update:modelValue', 'change'],
  directives: {
    clickOutside: {
      mounted(el, binding) {
        el.__clickOutsideHandler__ = (event) => {
          if (!(el === event.target || el.contains(event.target))) {
            binding.value(event)
          }
        }
        document.addEventListener('click', el.__clickOutsideHandler__)
      },
      unmounted(el) {
        document.removeEventListener('click', el.__clickOutsideHandler__)
      }
    }
  },
  setup(props, { emit }) {
    const showDropdown = ref(false)
    const selectedValues = ref([])

    watch(() => props.modelValue, (newVal) => {
      if (props.multiple) {
        selectedValues.value = Array.isArray(newVal) ? newVal : []
      } else {
        selectedValues.value = newVal !== null ? [newVal] : []
      }
    }, { immediate: true })

    const findNodeByValue = (nodes, value) => {
      for (const node of nodes) {
        if (node.value === value) {
          return node
        }
        if (node.children) {
          const found = findNodeByValue(node.children, value)
          if (found) return found
        }
      }
      return null
    }

    const displayValue = computed(() => {
      if (selectedValues.value.length === 0) return ''
      if (props.multiple) {
        return selectedValues.value.map(val => findNodeByValue(props.options, val)?.label || '').join(', ')
      } else {
        return findNodeByValue(props.options, selectedValues.value[0])?.label || ''
      }
    })

    const toggleDropdown = () => {
      if (props.disabled) return
      showDropdown.value = !showDropdown.value
    }

    const handleClickOutside = () => {
      showDropdown.value = false
    }

    const handleTreeChange = (newSelectedValues) => {
      selectedValues.value = newSelectedValues
      if (props.multiple) {
        emit('update:modelValue', newSelectedValues)
        emit('change', newSelectedValues)
      } else {
        const value = newSelectedValues.length > 0 ? newSelectedValues[0] : null
        emit('update:modelValue', value)
        emit('change', value)
        showDropdown.value = false // 单选时关闭下拉
      }
    }

    const handleClear = () => {
      selectedValues.value = []
      emit('update:modelValue', props.multiple ? [] : null)
      emit('change', props.multiple ? [] : null)
    }

    return {
      showDropdown,
      selectedValues,
      displayValue,
      toggleDropdown,
      handleClickOutside,
      handleTreeChange,
      handleClear
    }
  }
}
</script>

<style scoped>
.bx-tree-select {
  position: relative;
  display: inline-block;
  width: 240px;
  font-family: var(--bx-font-family);
}

.bx-tree-select--disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.bx-tree-select__input {
  display: flex;
  align-items: center;
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-medium);
  background: var(--bx-glass-bg);
  backdrop-filter: var(--bx-glass-blur);
  transition: all var(--bx-transition-medium);
  cursor: pointer;
  padding: 8px 12px;
}

.bx-tree-select__input:hover {
  border-color: var(--bx-glass-border-hover);
  background: var(--bx-glass-bg-hover);
}

.bx-tree-select--focused .bx-tree-select__input {
  border-color: rgba(0, 122, 255, 0.5);
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.1);
}

.bx-tree-select__input-field {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  color: var(--bx-text-primary);
  font-size: inherit;
  cursor: inherit;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.bx-tree-select__input-field::placeholder {
  color: var(--bx-text-tertiary);
}

.bx-tree-select__arrow {
  font-size: 14px;
  color: var(--bx-text-secondary);
  transition: transform var(--bx-transition-medium);
}

.bx-tree-select--focused .bx-tree-select__arrow {
  transform: rotate(180deg);
}

.bx-tree-select__clear {
  font-size: 14px;
  color: var(--bx-text-tertiary);
  cursor: pointer;
  margin-left: 8px;
}

.bx-tree-select__clear:hover {
  color: var(--bx-text-primary);
}

.bx-tree-select__dropdown {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  width: 100%;
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-medium);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  animation: bx-fade-in-up 0.2s ease-out;
  padding: 8px;
}

.bx-tree-select__empty {
  padding: 16px;
  text-align: center;
  color: var(--bx-text-tertiary);
}

@keyframes bx-fade-in-up {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bx-tree-select {
    width: 100%;
  }
}
</style>

